package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.DoctorLeftAdapter;
import com.xn.app.muying.adpter.DoctorRightAdapter;
import com.xn.app.muying.bean.DoctorGsonBean;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 科室选择
 * Created by Administrator on 2016/10/31.
 */
public class DoctorActivity extends BaseActivity implements HttpUtil.OnGetDataListener {
    //显示科室列表
    private ListView lv1 = null;
    //显示科室下分类
    private ListView lv2 = null;
    //标题
    private TextView hosptial_tv = null;
    //科室列表适配器
    private DoctorLeftAdapter doctorLeftAdapter = null;
    //科室下分类适配器
    private DoctorRightAdapter doctorRightAdapter = null;
    private Handler handler = new Handler();
    private ArrayList<DoctorGsonBean> list_bean;
    //页面传来的医院ID
    private int id = -1;
    //页面传来的医院名称
    private String title = "";
    private int mClickPosition;
    private int mLeftClickPosition;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor);
        //初始化组件
        initialization();
        //实现
        realize();
    }

    /**
     * 初始化组件，并给相应控件添加单击事件
     */
    private void initialization() {
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "医生介绍");
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        lv1 = (ListView) findViewById(R.id.activity_doctor_listview1);
        lv2 = (ListView) findViewById(R.id.activity_doctor_listview2);
        hosptial_tv = (TextView) findViewById(R.id.activity_doctor_tv);
        //返回键
        findViewById(R.id.activity_doctor_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //科室列表点击事件
        lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                doctorRightAdapter.getData((ArrayList<DoctorGsonBean.SubCompaniesBean>) list_bean.get(mClickPosition).getSubCompanies().get(i).getSubCompanies());
                mLeftClickPosition = i;
                doctorLeftAdapter.getSign(mLeftClickPosition);
            }
        });
        //科室下分类点击事件
        lv2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                intent.putExtra("doctorlist_id", list_bean.get(mClickPosition).getSubCompanies().get(mLeftClickPosition).getSubCompanies().get(i).getId() + "");
                intent.setClass(DoctorActivity.this, DoctorListActivity.class);
                startActivity(intent);
            }
        });
        //设置科室列表适配器
        doctorLeftAdapter = new DoctorLeftAdapter(DoctorActivity.this, handler, imageLoader, options);
        //设置科室下分类适配器
        doctorRightAdapter = new DoctorRightAdapter(DoctorActivity.this, handler);
        lv1.setAdapter(doctorLeftAdapter);
        lv2.setAdapter(doctorRightAdapter);
        //获取医院参数
        id = getIntent().getIntExtra("id", -1);
        title = getIntent().getStringExtra("name");
        hosptial_tv.setText(title);
    }

    //加载框
    AlertDialog dialog;

    /**
     * 功能实现
     */
    private void realize() {
        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            //获取科室及科室下分类信息
            HttpUtil.getData(APIMethod.Home_Doctor_Left, handler, DoctorActivity.this);
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }

    }

    /**
     * 获取科室及科室下分类信息
     *
     * @param data
     */
    @Override
    public void onJsonData(String data) {
        list_bean = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(data);
            JSONArray items = object.getJSONArray("items");
            for (int i = 0; i < items.length(); i++) {
                list_bean.add(new Gson().fromJson(items.get(i).toString(), DoctorGsonBean.class));
            }
            //如果没有选择医院设置默认
            if (id == -1) {
                hosptial_tv.setText(list_bean.get(0).getName());
                doctorLeftAdapter.getData(list_bean.get(0).getSubCompanies());
                doctorRightAdapter.getData((ArrayList<DoctorGsonBean.SubCompaniesBean>) list_bean.get(0).getSubCompanies().get(0).getSubCompanies());
            }
            //如果有设置医院
            for (int i = 0; i < list_bean.size(); i++) {
                if (list_bean.get(i).getId() == id) {
                    hosptial_tv.setText(list_bean.get(i).getName());
                    doctorLeftAdapter.getData(list_bean.get(i).getSubCompanies());
                    if (list_bean.get(i).getSubCompanies() != null && list_bean.get(i).getSubCompanies().size() > 1) {
                        mClickPosition = i;
                        mLeftClickPosition = 0;
                        doctorRightAdapter.getData((ArrayList<DoctorGsonBean.SubCompaniesBean>) list_bean.get(i).getSubCompanies().get(0).getSubCompanies());
                    }
                }
            }
            loginHandler.sendEmptyMessage(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    dialog.dismiss();
                    lv1.setVisibility(ListView.VISIBLE);
                    lv2.setVisibility(ListView.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

}
